package com.dahaonetwork.smartfactory.configure;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.security.web.util.matcher.RequestMatcher;

import com.dahaonetwork.smartfactory.constant.StaticParams;



/**
 * 此starter说明：微服务引入starter只需配置 @EnableOAuth2Sso 注解 即开启了oauth2授权
 * 引入此类声明了一个资源服务器。
 * @author liguobao
 *
 */


//@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
	@Override
	public void configure(HttpSecurity http) throws Exception {
//		//当前只授权swagger资源
//		
//		 http
//		    .antMatcher("/users")
//		        .authorizeRequests()
//		             .anyRequest().authenticated();
//		
//		http.authorizeRequests().antMatchers(SWAGGERUI.getSwaggerResource()).permitAll()
//		.and()
//		.authorizeRequests().requestMatchers(new IgnoredAuthRequestMatcher()).permitAll()
//		.anyRequest().authenticated();
//
//		// 设置通用的session创建策略

	 http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
		 http
         .csrf().disable()
         .exceptionHandling()
         .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
     .and()
         .authorizeRequests()
         .antMatchers(
 				StaticParams.PATHREGX.API, 
 				StaticParams.PATHREGX.CSS,
 				StaticParams.PATHREGX.JS,
 				StaticParams.PATHREGX.IMG).permitAll()
         .anyRequest().authenticated()//其余所有请求都需要认证后才可访问
     .and()
         .httpBasic();
		
//		http
//		.authorizeRequests()
//		.antMatchers(
//				StaticParams.PATHREGX.API, 
//				StaticParams.PATHREGX.CSS,
//				StaticParams.PATHREGX.JS,
//				StaticParams.PATHREGX.IMG).permitAll()//允许用户任意访问
//				.anyRequest().authenticated()//其余所有请求都需要认证后才可访问
//		.and()
//		.formLogin().loginPage("/login/login.do").
//		successHandler(new CustomSavedRequestAwareAuthenticationSuccessHandler())
//			//.loginPage("/login/login.do") // 这里不适用自定义的页面，使用springsecurity 默认提供的页面
////			.defaultSuccessUrl("/hello2")
//		.permitAll();//允许用户任意访问
//		
//		http.csrf().disable();
	
	}
	
	
	@Override
	public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
		resources.tokenServices(defaultTokenServices());
	}
	
	
	/**
	 * @Title: tokenStore @Description: 用户验证信息的保存策略 @param @return
	 * TokenStore @throws
	 */
//	@Autowired
//	private RedisConnectionFactory connectionFactory;
	
	@Autowired
	private DataSource dataSource;
	
	@Bean
	public TokenStore tokenStore() {
		//return new RedisTokenStore(connectionFactory);
		return new JdbcTokenStore(dataSource);
	}

	@Bean
	@Primary
	public DefaultTokenServices defaultTokenServices() {
		DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
		defaultTokenServices.setTokenStore(tokenStore());
		defaultTokenServices.setSupportRefreshToken(true);
		return defaultTokenServices;
	}
}